package elcom.model.connection;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.jconfig.Configuration;
import org.jconfig.ConfigurationManager;

import elcom.model.common.Log;

import oracle.jdbc.pool.OracleDataSource;

public class DBConnection {
	private static Connection con = null;
	private static OracleDataSource ods = null;

	public static Connection getConnection() {
		if (con == null) {
			try {
				createODS();
				con = ods.getConnection();
				con.setAutoCommit(false);
			}catch (Exception e) {
				e.printStackTrace();
				Log.logErr(e.toString());
			}
		}
		try {
			if (con.isClosed()) {
				con = ods.getConnection();
			}
		} catch (SQLException e) {
			ods = null;
			con = null;
			createODS();
			try {
				con = ods.getConnection();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.logErr(e.toString());
		}
		return con;
	}
	
	@SuppressWarnings({"deprecation" })
	private static void createODS(){
		Configuration config = ConfigurationManager
				.getConfiguration("MutilThreadConfig.xml");
		String URL = config.getProperty("URL",
				"jdbc:oracle:thin:@//192.168.6.112:1521/XE", "JDBC");
		String user = config.getProperty("USERNAME", "dv", "JDBC");
		String password = config.getProperty("PASSWORD", "dv", "JDBC");
		try {
			ods = new OracleDataSource();
			ods.setURL(URL);
			ods.setUser(user);
			ods.setPassword(password);
			ods.setConnectionCachingEnabled(false);

			Properties pro = new Properties();
			pro.setProperty("MinLimit", "1");
			pro.setProperty("MaxLimit", "5");
			pro.setProperty("InitialLimit", "1");
            pro.setProperty("ConnectionWaitTimeout", "5");
            pro.setProperty("ValidateConnection", "true");

			ods.setConnectionProperties(pro);
		} catch (Exception e) {
			e.printStackTrace();
			Log.logErr(e.toString());
		}
	}
}
